package com.ace.log.core

import com.ace.log.core.decorator.IDecorator
import com.ace.log.core.printer.ConsolePrinter
import com.ace.log.core.printer.IPrinter
import java.util.Collections

object L {

    private var TAG = "ACE_L"

    private var printers = Collections.synchronizedSet(mutableSetOf<IPrinter>())


    private var logLevel = LogLevel.DEBUG


    fun setLogLevel(level: LogLevel):L{
        logLevel = level
        return this
    }

    fun setTag(tag: String): L {
        TAG = tag
        return this
    }

    fun addPrinter(printer: IPrinter): L {
        this.printers.add(printer)
        return this
    }


    /****打印 start****/

    fun e(msg: String) = e(TAG, msg)

    fun e(tag: String, msg: String) = printLog(LogLevel.ERROR, tag, msg)

    fun w(msg: String) = w(TAG, msg)

    fun w(tag: String, msg: String) = printLog(LogLevel.WARN, tag, msg)

    fun i(msg: String) = i(TAG, msg)

    fun i(tag: String, msg: String) = printLog(LogLevel.INFO, tag, msg)

    fun d(msg: String) = d(TAG, msg)

    fun d(tag: String, msg: String) = printLog(LogLevel.DEBUG, tag, msg)

    private fun printLog(
        logLevel: LogLevel,
        tag: String,
        msg: String,
        set: Set<IPrinter> = printers
    ) {
        if (logLevel.value <= L.logLevel.value) {
            set.forEach {printer->

                //获取模版
                val template = getTemplateStr(printer.decorator)

                //输出log
                if (msg.contains("\n")) {
                    printer.printLog(
                        logLevel,
                        tag,
                        String.format(template, msg.replace("\n", "\n${printer.decorator.spliter()}"))
                    )
                } else {
                    printer.printLog(logLevel, tag, String.format(template, msg))
                }
            }
        }
    }

    /****打印 end****/

    /**
     * 模版
     */
     fun getTemplateStr(formatter: IDecorator): String {
        val stringBuilder = StringBuilder("  ")
        stringBuilder.append(formatter.top())
        stringBuilder.append("%s")
        stringBuilder.append(formatter.bottom())
        return stringBuilder.toString()
    }

}